package com.huafv.flyauth.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class CaptchaUtil {

    private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int WIDTH = 200;
    private static final int HEIGHT = 100;
    private static final int LENGTH = 4;
    private static final int FONT_SIZE = 50;

    public static String generateCode() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < LENGTH; i++) {
            int index = random.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }
        return sb.toString();
    }

    public static BufferedImage generateImage(String code) {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, WIDTH, HEIGHT);
        g2d.setFont(new Font("Arial", Font.BOLD, FONT_SIZE));
        for (int i = 0; i < LENGTH; i++) {
            int x = i * WIDTH / LENGTH + 10;
            int y = HEIGHT / 2 + FONT_SIZE / 2 - 10;
            g2d.setColor(new Color(50 + new Random().nextInt(100), 50 + new Random().nextInt(100), 50 + new Random().nextInt(100)));
            g2d.drawString(String.valueOf(code.charAt(i)), x, y);
        }
        g2d.dispose();
        return image;
    }

}
